import { getRandomKey, getStorage, getUserInfo, removeStorage, setStorage } from '@/utils/utils';
import { formatMsgByCn,myFormatMessage } from '@/utils/localeUtils';
import { isEmpty } from "lodash-es"
const userInfo = getStorage('userInfo') || {};
const locale = getStorage('umi_locale') || '';
export default {
  name:"global",
  state:{
    loginTimeout: false, // 标识是否登录会话过期了
    userInfo: userInfo,
    collapsed: false,
    siderWidth: 200,
    randomKey: '', // 随机数，用于强制重新渲染整个应用
    locale: locale, // 当前语言类型
  },
  effects:{
    // 登录成功之后，会触发这个 action ，以更新 state 的公用数据
    * afterLogin({ payload }, { call, put }) {
      const userInfo = getStorage('userInfo');

      yield put({
        type: 'loginTimeout',
        payload: false,
      });

      yield put({
        type: 'updateUserInfo',
        payload: userInfo,
      });
    },
  },
  reducers:{
    loginTimeout(state, { payload }) {
      return { ...state, loginTimeout: payload || false };
    },
    updateUserInfo(state, { payload }) {
      const { userInfo } = state;
      let newUserInfo;

      if (!isEmpty(payload)) {
        newUserInfo = { ...userInfo, ...payload };
      } else {
        newUserInfo = userInfo;
      }
      return {
        ...state, userInfo: newUserInfo,
      };
    },
    /**
     * 切换语言
     * @param state
     * @param payload
     * @returns {{randomKey: number, locale: *}}
     */
    updateRandomKey(state, { payload }) {
      return { ...state, randomKey: getRandomKey(), locale: payload };
    },
    /**
     * 设置 Menu 的展示与收缩
     * @param state
     * @param payload
     * @returns {{collapsed: *, siderWidth: number}}
     */
    changeLayoutCollapsed(state, { payload }) {
      return {
        ...state,
        collapsed: payload,
        siderWidth: payload ? 80 : 200,
      };
    },
  }
}
